//
//  AKLocalClient.m
//  AKLocalClient
//
//  Created by Yun Qing Teng on 11/13/06.
//  Copyright 2006 __MyCompanyName__. All rights reserved.
//

#import "AKLocalClient.h"
#import <netinet/in.h>
#import <arpa/inet.h>
#import <unistd.h>

@implementation AKLocalClient
- (id) init {
	self = [super init];
	if (self != nil) {
		browser = [[NSNetServiceBrowser alloc] init];
		services = [[NSMutableArray alloc] init];
		[browser setDelegate:self];
		
		[browser searchForServicesOfType:@"_ak._tcp." inDomain:@""];
	}
	return self;
}

- (NSArray *)availableServices {
	return services;
}

- (void)subscribeToService:(NSNetService *)aNetService {
	if (serviceBeingResolved) {
        [serviceBeingResolved stop];
        [serviceBeingResolved release];
        serviceBeingResolved = nil;
    }
	
	serviceBeingResolved = aNetService;
	[serviceBeingResolved retain];
	[serviceBeingResolved setDelegate:self];
	NSDictionary *dic = [[NSMutableDictionary alloc] init];
	[dic setValue:@"aaa" forKey:@"message"];
    NSData * representationToSend = [NSKeyedArchiver archivedDataWithRootObject:dic];
	[serviceBeingResolved setTXTRecordData:representationToSend];
	[serviceBeingResolved setTXTRecordData:representationToSend];
	[serviceBeingResolved resolveWithTimeout:5];
}

- (void)unsubscribe {
	
}

- (void)sendMessage:(NSString *)aMessage {
	NSLog(@"%@", aMessage);
	unichar *buffer;
	unsigned char byte;
	int length;
	unsigned int result;
	
	int i;
	
	buffer = malloc(MAX_BUFFER_SIZE * sizeof(unichar));
	[aMessage getCharacters:buffer];
	
	
	for (i = 0; i < [aMessage length]; i ++) {
		NSLog(@"%d--------%c", i, buffer[i]);
	}
	
	length = sizeof(unichar) * [aMessage length];
	byte = (unsigned char)length;
	
	result = write(user.fd, &byte, 1);
	if (result <= 0) {
		NSLog(@"write error");
		return;
	}
	
	do {
		result = write(user.fd, buffer, length);
		if (result <= 0) {
			NSLog(@"write eror");
			return;
		}
		
		NSLog(@"%d", result);
		length -= result;
		buffer += result;
	} while (length > 0);
}

- (void)sendNewMoveWithChessIndex:(unsigned)aIndex step:(unsigned)newStep {
	
}

- (void)netServiceBrowser:(NSNetServiceBrowser *)aNetServiceBrowser didFindService:(NSNetService *)aNetService moreComing:(BOOL)moreComing {
    NSLog(@"fsgfd");
	[services addObject:aNetService];
}

- (void)netServiceDidResolveAddress:(NSNetService *)sender {
    if ([[sender addresses] count] > 0) {
        NSData * address;
        struct sockaddr * socketAddress;
        NSString * ipAddressString = nil;
        NSString * portString = nil;
        int socketToRemoteServer;
        char buffer[256];
        int index;
		
        // Iterate through addresses until we find an IPv4 address
        for (index = 0; index < [[sender addresses] count]; index++) {
            address = [[sender addresses] objectAtIndex:index];
            socketAddress = (struct sockaddr *)[address bytes];
			
            if (socketAddress->sa_family == AF_INET) break;
        }
		
		
        if (socketAddress) {
            switch(socketAddress->sa_family) {
                case AF_INET:
                    if (inet_ntop(AF_INET, &((struct sockaddr_in *)socketAddress)->sin_addr, buffer, sizeof(buffer))) {
                        ipAddressString = [NSString stringWithCString:buffer];
                        portString = [NSString stringWithFormat:@"%d", ntohs(((struct sockaddr_in *)socketAddress)->sin_port)];
                    }
                    
                    // Cancel the resolve now that we have an IPv4 address.
                    [sender stop];
                    [sender release];
                    serviceBeingResolved = nil;
					
                    break;
                case AF_INET6:
                    // PictureSharing server doesn't support IPv6
                    return;
            }
        }
		
        socketToRemoteServer = socket(AF_INET, SOCK_STREAM, 0);
		
		if (socketToRemoteServer == -1) {
			NSLog(@"%s", strerror(errno));
		}
		int result = fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
		
		if (result == -1) {
			NSString *error = [[NSString alloc] initWithCString:strerror(errno)];
			NSLog(@"%@", error);
			return;
		}
		
        if(socketToRemoteServer > 0) {
			if(connect(socketToRemoteServer, (struct sockaddr *)socketAddress, sizeof(*socketAddress))  != -1) {
				user.fd = socketToRemoteServer;
				FD_ZERO(&userfd);
				FD_SET(socketToRemoteServer, &userfd);
			}
			
			/*
            NSFileHandle * remoteConnection = [[NSFileHandle alloc] initWithFileDescriptor:socketToRemoteServer closeOnDealloc:YES];
            if(remoteConnection) {
                [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(readAllTheData:) name:NSFileHandleReadToEndOfFileCompletionNotification object:remoteConnection];
                if(connect(socketToRemoteServer, (struct sockaddr *)socketAddress, sizeof(*socketAddress)) == 0) {
                    //[remoteConnection readToEndOfFileInBackgroundAndNotify];
                }
            } else {
                close(socketToRemoteServer);
            }
			*/
        }
    }
	
	if ([delegate respondsToSelector:@selector(subscribingDidSucceed)]) {
		[delegate subscribingDidSucceed];
	}
}

- (void)setDelegate:(id)aDelegate {
	[aDelegate retain];
	[delegate release];
	
	delegate = aDelegate;
}
@end
